package com.example.order.message;

import com.example.order.utils.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.imooc.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/6/14 18:16
 */
@Component
@Slf4j
public class ProductInfoReceiver {

    // %s 表示商品id
    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @SuppressWarnings("unchecked")
    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void processProductInfo(String message) {
        // message -> List<ProductInfoOutput>
        // 消息发送的是一个列表，所以需要特殊json转换

        List<ProductInfoOutput> productInfoOutputList = (List<ProductInfoOutput>) JsonUtil.fromJson(message,
                new TypeReference<List<ProductInfoOutput>>() {});
        log.info("从队列【{}】收到消息】productInfoOutputList={}", "productInfo", productInfoOutputList);


        // 将商品信息存储到redis中，我们仅仅存储库存数
        for (ProductInfoOutput productInfoOutput : productInfoOutputList) {
            stringRedisTemplate.opsForValue().set(
                    String.format(PRODUCT_STOCK_TEMPLATE, productInfoOutput.getProductId()),
                    String.valueOf(productInfoOutput.getProductStock()));
        }
    }
}
